package ps.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import ps.server.net.ClientInfo;
import ps.server.rights.User;



public class ClientInfoContent implements PacketContent {
    
    ClientInfo[] clientInfos;
    
    ClientInfoContent() {
    }
    
    public ClientInfoContent(ClientInfo[] clientInfos) {
        this.clientInfos = clientInfos;
    }
    
    @Override
    public void writeContent(OutputStream out) throws IOException {
        // write count
        out.write(clientInfos.length);
        
        for (int i = 0; i < clientInfos.length; i++) {
            // write ping
            Packet.write2ByteNumber(out, clientInfos[i].getPing());
            // write status byte
            out.write(
                    (clientInfos[i].isAfk() ? 1 : 0) +
                    (clientInfos[i].getUser().getRight() == User.RIGHT_ADMIN ? 2 : 0) +
                    (clientInfos[i].isLogReadActive() ? 4 : 0) +
                    (clientInfos[i].isLinkDead() ? 8 : 0)
            );
            // write group number
            out.write(clientInfos[i].getGroupNumber());
        }
    }
    
    @Override
    public void readContent(InputStream in) throws IOException {
        // read count
        int count = in.read();
        clientInfos = new ClientInfo[count];
        for (int i = 0; i < count; i++) {
            clientInfos[i] = new ClientInfo();
            
            // read ping
            clientInfos[i].setPing(Packet.read2ByteNumber(in));
            // read status byte
            int status = in.read();
            // set afk
            clientInfos[i].setAfk((status & 1) > 0);
            // set user rights
            User user = new User();
            user.setAdmin((status & 2) > 0);
            clientInfos[i].setUser(user);
            // set log read status
            clientInfos[i].setLogReadActive((status & 4) > 0);
            // set link dead
            clientInfos[i].setLinkDead((status & 8) > 0);
            // read group number
            clientInfos[i].setGroupNumber(in.read());
        }
    }
    
    @Override
    public String toString() {
        String ret = "[ ClientInfo | ";
        for (int i = 0; i < clientInfos.length; i++) {
            ret += "[";
            ret += " ping=\"" + clientInfos[i].getPing() + "\"";
            ret += " afk=\"" + clientInfos[i].isAfk() + "\"";
            ret += " admin=\"" + clientInfos[i].getUser().isAdmin() + "\"";
            ret += " logReadAvtive=\"" + clientInfos[i].isLogReadActive() + "\"";
            ret += " groupNumber=\"" + clientInfos[i].getGroupNumber() + "\"";
            ret += " ]";
        }
        ret += " ]";
        
        return ret;
    }
    
    public ClientInfo[] getClientInfos() {
        return clientInfos;
    }
}
